package com.tomatozq.receiver;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tomatozq.dto.DocumentInfo;
import com.tomatozq.util.PDFBuilder;
import com.tomatozq.util.Word2PDFConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sun.rmi.transport.ObjectTable;

import java.io.File;
import java.nio.file.Path;

@Slf4j
@Component
@RabbitListener(queues = "${document.queue.name}")
public class DocumentReceiver {
    @RabbitHandler
    public void process(DocumentInfo documentInfo) {
        ObjectMapper mapper =  new ObjectMapper();

        try {
            log.info("接收到消息:" + mapper.writeValueAsString(documentInfo));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        String srcFilePath = documentInfo.getSrcFilePath();

        if (!new File(srcFilePath).exists()){
            log.error(srcFilePath + "不存在");
            return;
        }

        String ext = srcFilePath.substring(srcFilePath.lastIndexOf(".") + 1).toLowerCase();

        String fileName = srcFilePath.substring(srcFilePath.lastIndexOf(File.separator) + 1);

        String markImagePath = "G:/watermark/watermark.png";

        String pdfFilePath = "";

        long start = System.currentTimeMillis();

        if (ext.equals("doc") || ext.equals("docx")){
            pdfFilePath = srcFilePath.substring(0,srcFilePath.length() - ext.length() - 1) + ".pdf";
            Word2PDFConverter.convertByOpenOffice(srcFilePath,pdfFilePath);

            log.info("转pdf耗时:" + (System.currentTimeMillis() - start) + "ms");
        }
        else if(ext.equals("pdf")){
            pdfFilePath = srcFilePath;
        }

        if (StringUtils.isEmpty(pdfFilePath)){
            log.error("文件格式必须是doc,docx,pdf其中之一!" + fileName);
            return;
        }

        String name = fileName.substring(0,fileName.length() - ext.length() - 1);
        String destFilePath = "G:/watermark/" +  name + "(水印).pdf";

        start = System.currentTimeMillis();

        PDFBuilder builder = new PDFBuilder(pdfFilePath,markImagePath,destFilePath);
        builder.create();

        log.info("文档加水印及页码耗时:" + (System.currentTimeMillis() - start) + "ms");
    }
}
